//
//  TimerViewController.swift
//  DemoExtensionToday
//
//  Created by 唐可雄 on 16/5/13.
//  Copyright © 2016年 swustyc. All rights reserved.
//

import UIKit

let defaultTimeInterval: NSTimeInterval = 5

class TimerViewController: UIViewController {
    
    @IBOutlet weak var timeLabel: UILabel!
    
    var timer: Timer!
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // MARK: Private Methods
    
    private func updateLabel() {
        timeLabel.text = timer.leftTimeStr
    }
    
    private func showFinishAlert(finished: Bool) {
        let ac = UIAlertController(title: nil, message: finished ? "Finished" : "Stopped", preferredStyle: .Alert)
        
        ac.addAction(UIAlertAction(title: "Ok", style: .Default, handler: { [weak ac] action in
            ac!.dismissViewControllerAnimated(true, completion: nil)
        }))
        
        presentViewController(ac, animated: true, completion: nil)
        
    }
    
    // MARK: Event Response
    
    /// did click start button
    @IBAction func startBtnDidClick(sender: AnyObject) {
        if timer == nil {
            timer = Timer(timeInterval: defaultTimeInterval)
        }
        
        let (started, error) = timer.start({ (progress) in
                self.updateLabel()
            }, stopHandler: { (finished) in
                self.showFinishAlert(finished)
                self.timer = nil
        })
        
        if started {
            updateLabel()
        } else {
            if let realError = error {
                print("error: \(realError.code)")
            }
        }
    }
    
    /// did click end button
    @IBAction func stopBtnDidClick(sender: AnyObject) {
        if let realTimer = timer {
            let (stopped, error) = realTimer.stop()
            if !stopped {
                if let realError = error {
                    print("error: \(realError.code)")
                }
            }
            
        }
    }
}

